package com.ucar.train.web;

import com.ucar.train.dto.User;
import com.ucar.train.dto.UserRole;
import com.ucar.train.service.RoleService;
import com.ucar.train.service.UserService;
import com.ucar.train.utils.JodaUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * @author wufuqiang
 * @title: UserController
 * @projectName:train-parent
 * @description: T0D0
 * @created 2019-07-24 15:12
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    /**
     * 返回登入页面
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";//返回登录页面
    }

    /**
     * 登入操作
     *
     * @param user
     * @param req
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, HttpServletRequest req, Model model) {
        // 1、获取subject
        Subject subject = SecurityUtils.getSubject();
        //2、封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(user.getPhone(), user.getPassword());

        try {
            subject.login(token); // 没有异常则说明登录成功
            HttpSession session = req.getSession();
            User userTemp = (User) subject.getPrincipal();
            session.setAttribute("id", userTemp.getId());
            session.setAttribute("name", userTemp.getName());
            return "index";
        } catch (UnknownAccountException e) {
            // 登录失败：用户名不存在
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            // 登录失败：密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    /**
     * 用户注销登出
     *
     * @return 返回登入页面
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        session.removeAttribute("id");
        subject.logout();
        return "login";
    }

    /**
     * 返回注册页面
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "register";//返回注册页面
    }

    /**
     * 注册操作
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(User user, Model model) {
        Integer result = userService.register(user);
        //注册成功
        if (result == 1) {
            model.addAttribute("msg", "注册成功");
            return "login";//返回登入页面
        }
        //注册失败
        model.addAttribute("msg", "手机号或邮箱已存在");
        return "register";//返回注册页面
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @RequestMapping(value = "/listUsers", method = RequestMethod.GET)
    public String listUsers(Model model) {
        List<User> users = userService.listUsers();
        model.addAttribute("users", users);
        return "user-list";
    }

    /**
     * 查询owner所有组用户
     *
     * @param id owner id
     * @return
     */
    @RequestMapping(value = "/listUsersByGroup", method = RequestMethod.GET)
    public String listUsersByGroup(Model model, Long id) {
        List<User> users = userService.listUserByGroupId(id);
        model.addAttribute("users", users);
        return "user-list";
    }

    /**
     * 返回添加用户页面
     *
     * @return
     */
    @RequestMapping(value = "/saveUser", method = RequestMethod.GET)
    public String saveUserView() {
        return "user-add";
    }

    /**
     * 管理员添加新用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public String saveUser(User user, Model model) {
        Integer result = userService.saveUser(user);
        if (result == 1) {
            model.addAttribute("msg", "添加成功");
            return "redirect:listUsers";
        }
        model.addAttribute("msg", "添加失败，用户已存在");
        return "user-add";
    }

    /**
     * 返回修改用户信息页面
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "updateUser", method = RequestMethod.GET)
    public String updateUser(Model model, Long id) {
        User user = userService.getUser(id);
        model.addAttribute("user", user);
        return "user-show";
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    public String updateUser(User user) {
        user.setModifyTime(JodaUtils.nowAsDate());
        userService.updateUser(user);
        return "redirect:listUsers";
    }

    /**
     * 根据用户id删除用户,删除用户组关系，删除用户角色关系
     *
     * @param id 用户id
     * @return
     */
    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    public String deleteUser(Long id) {
        userService.deleteUser(id);
        return "redirect:listUsers";
    }

    /**
     * 查看用户个人信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public String getUser(Model model, Long id) {
        User user = userService.getUser(id);
        model.addAttribute("user");
        return "user-show";
    }

    /**
     * 查看用户的所有角色信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/listRoleByUser", method = RequestMethod.GET)
    public String listRoleByUser(Model model, Long id) {
        List<UserRole> userRoles = userService.listRoleByUser(id);
        model.addAttribute("userroles", userRoles);
        return "userrole-list";
    }

    @RequestMapping("/noAuth")
    public String noAuth() {
        return "noAuth";
    }
}
